package com.agh.portal.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.agh.portal.domain.Answer;

@RequestMapping("/answers")
@Controller
@RooWebScaffold(path = "answers", formBackingObject = Answer.class)
@RooWebFinder
public class AnswerController {
	
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Answer answer, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, answer);
            return "answers/create";
        }
        uiModel.asMap().clear();
        answer.setCreationDate(new Date());
        answer.persist();
        return "redirect:/questions/" + encodeUrlPathSegment(answer.getQuestion().getId().toString(), httpServletRequest);
    }
	
    @RequestMapping(produces = "text/html")
    public String list(
    		@RequestParam(value = "page", required = false) Integer page, 
    		@RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
              
            List<Answer> answers = Answer.findAnswerEntries(firstResult, sizeNo);

            uiModel.addAttribute("answers", answers);
            
            float nrOfPages = (float) Answer.countAnswers() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("answers", Answer.findAllAnswers());
        }
        return "answers/list";
    }
}
